<template>
  <div class="container">
    <TableWrapper :title="'字典数据 [ ' + dictName + ' ]'">
      <template #close>
        <el-button
          style="font-size: 26px"
          icon="el-icon-close"
          type="text"
          @click="$emit('close')"
        ></el-button>
      </template>
      <!-- 搜索头 -->
      <template #header>
        <el-form ref="form" :model="query" label-width="100px" :inline="true">
          <el-form-item label="字典标签：">
            <el-input
              v-model="query.dictLabel"
              placeholder="请输入字典标签"
            ></el-input>
          </el-form-item>
          <el-form-item label="字典状态：">
            <el-select v-model="query.status" placeholder="请选择字典状态">
              <el-option
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="ml15">
            <el-button
              icon="el-icon-search"
              type="primary"
              @click="searchChange"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh-left" @click="searchReset"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </template>

      <!-- 表体 -->
      <template #main>
        <div style="margin-bottom: 18px">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            @click="beforeOpen('add')"
            v-hasPermission="['system:dict:add']"
            >新增</el-button
          >
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            :disabled="selectionList.length != 1"
            v-hasPermission="['system:dict:edit']"
            >修改</el-button
          >
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            :disabled="selectionList.length == 0"
            v-hasPermission="['system:dict:delete']"
            >批量删除</el-button
          >
          <el-button
            type="success"
            plain
            icon="el-icon-refresh"
            @click="refreshChange"
            v-hasPermission="['system:dict:query']"
            >刷新缓存</el-button
          >
        </div>
        <el-table
          align="center"
          :data="data"
          :header-cell-style="headStyle"
          @selection-change="selectionChange"
        >
          <el-table-column align="center" type="selection" width="50">
          </el-table-column>
          <el-table-column align="center" prop="dictCode" label="字典编码">
          </el-table-column>
          <el-table-column align="center" prop="dictLabel" label="字典标签">
          </el-table-column>
          <el-table-column align="center" prop="dictValue" label="字典键值">
          </el-table-column>
          <el-table-column align="center" prop="dictSort" label="字典排序">
          </el-table-column>
          <el-table-column align="center" prop="status" label="状态">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.status === '0' ? 'success' : 'danger'"
                disable-transitions
                >{{ scope.row.status === "0" ? "正常" : "停用" }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column align="center" prop="remark" label="备注">
          </el-table-column>
          <el-table-column align="center" prop="createTime" label="创建时间">
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-edit"
                size="small"
                @click="beforeOpen('edit', scope.row)"
                v-hasPermission="['system:dict:edit']"
                >编辑</el-button
              >
              <el-button
                type="text"
                @click="handelDel(scope.row.dictCode)"
                v-hasPermission="['system:dict:delete']"
                icon="el-icon-delete"
                size="small"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
    </TableWrapper>

    <!-- 修改框 -->
    <el-dialog
      :title="(ntype == 'add' ? '添加' : '修改') + '字典数据'"
      :visible.sync="dialogVisible"
      append-to-body
      width="500px"
    >
      <el-form ref="formRef" :rules="rules" :model="form" label-width="100px">
        <el-form-item label="字典类型：">
          <el-input v-model="form.dictType" :disabled="true" />
        </el-form-item>
        <el-form-item label="数据标签：" prop="dictLabel">
          <el-input v-model="form.dictLabel" placeholder="请输入数据标签" />
        </el-form-item>
        <el-form-item label="数据键值：" prop="dictValue">
          <el-input v-model="form.dictValue" placeholder="请输入数据键值" />
        </el-form-item>
        <el-form-item label="样式属性：" prop="cssClass">
          <el-input v-model="form.cssClass" placeholder="请输入样式属性" />
        </el-form-item>
        <el-form-item label="显示排序：" prop="dictSort">
          <el-input-number
            style="width: 50%"
            v-model="form.dictSort"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="回显样式：" prop="listClass">
          <el-select v-model="form.listClass">
            <el-option
              v-for="item in listClassOptions"
              :key="item.value"
              :label="item.label + '(' + item.value + ')'"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态：">
          <el-radio-group value="0" v-model="form.status">
            <el-radio
              v-for="item in dict.type.sys_normal_disable"
              :key="item.raw.dictCode"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
            placeholder="请输入备注内容"
            maxlength="500"
            type="textarea"
            resize="none"
            show-word-limit
            v-model="form.remark"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave()" :loading="loading"
          >保 存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import TableWrapper from "@/components/Table/TableWrapper.vue";
import {
  getList,
  remove,
  update,
  getNotice,
  add,
} from "@/api/system/dictData.js";

export default {
  components: { TableWrapper },
  dicts: ["sys_normal_disable"],
  props: {
    queryType: {
      type: String,
      default: "",
    },
    dictName: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      // 搜索数据
      query: {},
      // 多选数据
      selectionList: [],
      // 表数据
      data: [],
      // 弹出框数据
      form: {},
      // 控制弹出框
      dialogVisible: false,
      // 操作类型
      ntype: "add",
      // 按钮
      loading: false,
      // 校验结果
      validate: false,
      // 表单验证规则
      rules: {
        dictLabel: [
          { required: true, message: "数据标签不能为空", trigger: "blur" },
        ],
        dictValue: [
          { required: true, message: "数据键值不能为空", trigger: "blur" },
        ],
        dictSort: [
          { required: true, message: "数据顺序不能为空", trigger: "blur" },
        ],
      },
      // 数据标签回显样式
      listClassOptions: [
        {
          value: "default",
          label: "默认",
        },
        {
          value: "primary",
          label: "主要",
        },
        {
          value: "success",
          label: "成功",
        },
        {
          value: "info",
          label: "信息",
        },
        {
          value: "warning",
          label: "警告",
        },
        {
          value: "danger",
          label: "危险",
        },
      ],
    };
  },
  created() {
    // 获取数据
    this.refreshChange();
  },
  methods: {
    // 搜索重置
    searchReset() {
      this.query = {};
      this.refreshChange();
    },
    // 搜索点击
    searchChange() {
      this.refreshChange();
    },
    // 多选发生改变
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
    },
    // 刷新数据
    refreshChange() {
      this.onLoad(this.query);
    },
    // 重置表单
    resetForm() {
      this.form = {
        dictType: this.queryType,
        dictLabel: undefined,
        dictValue: undefined,
        cssClass: undefined,
        dictSort: 0,
        listClass: "default",
        status: "0",
        remark: undefined,
      };
    },
    // 校验表单
    validateForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.validate = true;
          return true;
        } else {
          this.validate = false;
          return false;
        }
      });
    },
    // 处理表单开启
    beforeOpen(ntype, row) {
      this.ntype = ntype;
      // 重置标签
      this.resetForm();

      // 如果是编辑
      if (["edit", "view"].includes(ntype)) {
        // 查询详情
        getNotice(row.dictCode).then((res) => {
          res.data.listClass =
            res.data.listClass == "" ? "default" : res.data.listClass;
          this.form = res.data;
        });
      }

      // 修改按钮状态
      this.loading = false;
      // 打开提交框
      this.dialogVisible = true;
    },
    // 添加数据
    handleSave() {
      // 校验表单
      this.validateForm();

      if (!this.validate) {
        return;
      }

      if (this.ntype == "add") {
        this.sendAjax(add, this.form);
      } else {
        this.sendAjax(update, this.form);
      }
    },
    // 发送 ajax 请求
    sendAjax(Interface, row) {
      // 调用接口发送请求
      Interface(row).then(
        (res) => {
          if (res.code == 200) {
            this.$modal.msgSuccess(res.msg);
            // 关闭弹窗
            this.dialogVisible = false;
            // 刷新列表
            this.refreshChange();
          } else {
            this.$modal.msgError(res.msg);
          }
          this.loading = false;
        },
        () => {
          this.$modal.msgError("系统错误，请稍后尝试！");
        }
      );
    },
    // 删除数据
    handelDel(ids) {
      this.$modal
        .confirm("确定将选择数据删除?")
        .then(() => {
          return remove(ids);
        })
        .then(() => {
          this.refreshChange();
          this.$modal.msgSuccess("操作成功!");
        });
    },
    // 重载数据
    onLoad(params = {}) {
      if (this.queryType == null || this.queryType == "") {
        return;
      }

      let values = {
        ...params,
        // 排序字段
        orderByColumn: "create_time",
        // 排序方式 desc 降序 asc 升序
        isAsc: "desc",
      };

      // 传递日期
      if (values.createTime && values.createTime.length == 2) {
        values.beginTime = params.createTime[0];
        values.endTime = params.createTime[1];
      }

      this.loading = true;
      getList(this.queryType, Object.assign(values, this.query)).then((res) => {
        this.data = res.data;
        this.selectionClear();
      });
    },
    // 自定义表头颜色
    headStyle({ row, rowIndex }) {
      if (rowIndex === 0) {
        return {
          backgroundColor: "#F8FAFF",
          fontWeight: 800,
          color: "#515a6e",
        };
      }
    },
  },
};
</script>